<template>
  <div class="common-layout">
    <el-container>
      <el-header class="header">
        <el-text class="header-text">抢点班作业后台管理</el-text>
        <el-button class="header-button" type="primary" text style="float: right;" @click="logout">退出登录</el-button>
      </el-header>
      <el-main class="main">
        <div class="main-title">
          抢点班作业列表
        </div>
        <div class="list">
          <el-button class="main-button" type="primary" style="float: left;" @click="newAssignment">新建作业</el-button>
          <el-table :data="assignments" style="width: 100%" :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }">
            <el-table-column label="序号">
              <template #default="scope">
                {{ scope.$index + (PageNo - 1) * PageSize + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="作业名称"></el-table-column>
            <el-table-column label="内容归属">
              <template v-slot="scope">
                <span v-if="scope.row.clubType == '1'">牧民俱乐部</span>
                <span v-else-if="scope.row.clubType == '2'">博古论坛</span>
                <span v-else-if="scope.row.clubType == '3'">神枪手俱乐部</span>
                <span v-else-if="scope.row.clubType == '4'">环球俱乐部</span>
                <span v-else-if="scope.row.clubType == '5'">价值投资</span>
                <span v-else-if="scope.row.clubType == '6'">波段行情</span>
                <span v-else-if="scope.row.clubType == '7'">抄底卖顶</span>
                <span v-else-if="scope.row.clubType == '8'">资金及仓位管理</span>
                <span v-else-if="scope.row.clubType == '9'">财富的游戏</span>
              </template>
            </el-table-column>
            <el-table-column prop="article" label="关联文章">
              <template #default="{ row }">
                <el-tooltip class="tooltip" v-if="row.article" :content="row.article.title" placement="bottom"
                  :disabled="row.article.title.length <= 10" effect="light">
                  {{ row.article.title.slice(0, 10) || '—' }}
                </el-tooltip>
                <span v-else>—</span>
              </template>
            </el-table-column>
            <el-table-column prop="live" label="关联直播">
              <template #default="{ row }">
                <el-tooltip class="tooltip" v-if="row.live" :content="row.live.name" placement="bottom"
                  :disabled="row.live.name.length <= 10" effect="light">
                  {{ row.live.name.slice(0, 10) || '—' }}
                </el-tooltip>
                <span v-else>—</span>
              </template>
            </el-table-column>
            <el-table-column prop="count" label="填写份数"></el-table-column>
            <el-table-column label="提交时间">
              <template v-slot="scope">
                {{ scope.row.startDate.split(' ')[0] }} 至 {{ scope.row.endDate.split(' ')[0] }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <span v-if="row.status === 0">未发布</span>
                <span v-else-if="row.status === 1">发布中</span>
                <span v-else-if="row.status === 2">已下架</span>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="发布时间"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" link @click="viewDetails(scope.row)">查看明细</el-button>
                <el-button type="primary" link v-if="scope.row.status != '2'" @click="editAssignment(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>

        </div>
        <div class="page">
          <el-pagination v-model:current-page="PageNo" v-model:page-size="PageSize" :page-sizes="[20, 50, 100, 200]"
            :size="size" :disabled="disabled" :background="background" layout="total,prev,next,sizes,jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import ClassListApi from '../api/ClassListApi';
import axios from 'axios';
import { useRouter } from 'vue-router';
import LoginApi from '../api/LoginApi';
import { useTokenStore } from '../stores/token';
import { useUserStore } from '../stores/user';

const router = useRouter();

const assignments = ref([]);

// 初始化页码，这里假设初始页码为1，你可以根据实际需求修改
const PageNo = ref(1);
// 初始化页面大小，这里假设初始页面大小为10，同样可按需修改
const PageSize = ref(20);
const size = ref('default');
const disabled = ref(false);
const background = ref(true);
const total = ref(0);
// 处理页面大小改变的事件函数，将新的页面大小赋值给PageSize变量
const handleSizeChange = (newPageSize) => {
  PageSize.value = newPageSize;
  getAssignments(PageNo.value, PageSize.value);
};

// 处理当前页码改变的事件函数，将新的页码赋值给PageNo变量
const handleCurrentChange = (newPageNo) => {
  PageNo.value = newPageNo;
  getAssignments(PageNo.value, PageSize.value);
};
const getAssignments = (PageNo, PageSize) => {
  ClassListApi.getClassList(PageNo, PageSize)
    .then((response) => {
      assignments.value = response.data.list;
      total.value = response.data.total;
      console.log(assignments.value);
    })
    .catch((error) => {
      console.error('获取作业列表失败', error);
    });
};
//在组件初始化时（类似mounted生命周期的效果）获取一次初始数据
onMounted(() => {
  getAssignments(PageNo.value, PageSize.value);
  const token = useTokenStore();
  console.log(token);
  console.log(token.value);
  console.log(token.token)
  console.log("=============");
});

const newAssignment = () => {
  router.push('/addwork')
}

// 查看明细按钮的点击事件处理函数
const viewDetails = async(row) => {
  try {
    router.push({
      name: 'workdetail',
      params: { id: row.id },
    });
    console.log(row.id)
  } catch (error) {
    console.log('获取数据出错:', error)
  }
};


// 编辑按钮的点击事件处理函数
const editAssignment = async (row) => {
  try {
    router.push({
      name: 'updatework',
      params: { id: row.id },
    });
    console.log(row.id)
  } catch (error) {
    console.log('获取数据出错:', error)
  }
};
// // 退出登录
// const logout = () => {
//     LoginApi.logout().then(res => {
//         console.log(res);
//         // 移除axios请求拦截器中设置token的逻辑，恢复到初始状态
//         // axios.interceptors.request.eject(axios.interceptors.request.handlers.find(
//         //     handler => handler.fulfilled && handler.fulfilled.toString().includes('token')
//         // ));
//         config.headers['token'] = ` `;
//     }).catch(err => {
//         // 处理退出登录接口调用失败的情况，比如提示错误信息等
//         ElMessage.error('退出登录失败，请稍后重试');
//     }).finally(() => {
//         // 无论接口调用成功与否，都进行页面跳转
//         router.push('/');
//     });
// }
// //退出登录
// const logout = () => {
//   LoginApi.logout().then(res => {
//     console.log(res)
//   })
//   router.push('/')
// }  

//退出
const logout=async()=>{
  try {
    await LoginApi.logout()
  } catch (error) {
    console.log(error)
  }
    //清除登录信息
    const tokenStore = useTokenStore();
    const userStore = useUserStore();
    tokenStore.clear();
    userStore.clear();
  router.push('/')
}
</script>

<style scoped>
.page {
  margin-left: 70%;
}

.header {
  height: 100px;
  line-height: 100px;
  padding: 0 80px;
}

.header-text {
  font-size: 22px;
  font-weight: 500;
  color: black;
  float: left;
}

.header-button {
  margin-top: 30px;
}

.main {
  padding: 20px 203px;
  background-color: #F8F8F8;
}

.list {
  padding: 0 60px;
  background-color: white;
}

.main-title {
  font-size: 16px;
  background-color: white;
  font-weight: bold;
  height: 52px;
  border-bottom: 2px solid #ececec;
  padding: 0 60px;
  line-height: 52px;
}

.main-button {
  margin: 15px 0;
  padding: 12px 20px;
  height: 40px;
}
</style>